package dev.alm.cqtakeoutservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import dev.alm.cqtakeoutservice.entity.User;
import dev.alm.cqtakeoutservice.mapper.UserMapper;
import dev.alm.cqtakeoutservice.service.UserService;
import dev.alm.cqtakeoutservice.utils.JedisUtil;
import dev.alm.cqtakeoutservice.utils.JwtUtil;
import dev.alm.cqtakeoutservice.utils.Md5Util;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public String login(User user) throws Exception {
        String username = user.getUsername();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user1 = userMapper.selectOne(wrapper);
        if (user1 == null) {
            return null;
        }
        // 检查加密后的密码是否正确
        if (!Md5Util.decrypt(user.getPassword(), user1.getPassword())) {
            return null;
        }

        // 检查 redis 中是否已经存在相应的 token 缓存记录
        String token = JedisUtil.get(username);
        if (token == null) {
            token = JwtUtil.generateJwtToken(username);
            JedisUtil.set(username, token);
        }
        return token;
    }

    @Override
    public User getUserByUsername(String username) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        return userMapper.selectOne(wrapper);
    }

    @Override
    public User add(User user) throws Exception {
        String encrypt = Md5Util.encrypt(user.getPassword());
        user.setPassword(encrypt);
        int insert = userMapper.insert(user);
        if (insert == 0) {
            return null;
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        return userMapper.selectOne(wrapper);
    }

    @Override
    public List<User> list() {
        return userMapper.selectList(null);
    }

    @Override
    public User getUserByUsernameAndEmail(String username, String email) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        wrapper.eq("email", email);
        return userMapper.selectOne(wrapper);
    }

    @Override
    @CacheEvict(cacheNames = "list", allEntries = true)
    public Boolean removeListCache() {
        return true;
    }

    @Override
    @CacheEvict(cacheNames = "getUserByUsername", allEntries = true)
    public Boolean removeByUsername() {
        return true;
    }

    @Override
    public Boolean removeUserCache() {
        this.removeListCache();
        this.removeByUsername();
        return true;
    }




}
